<template>
    <div class="add-product-container">
        <div class="content-wrapper">
            <div class="header-section">
                <h2 class="page-title">
                    <i class="el-icon-plus"></i>
                    添加商品
                </h2>
                <p class="page-subtitle">发布优质商品，开启销售之路</p>
            </div>
            
            <div class="form-card">
                <el-form 
                    :model="form" 
                    :rules="rules" 
                    ref="formEl"
                    label-width="100px"
                    class="product-form"
                >
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="商品名称" prop="name">
                                <el-input 
                                    v-model="form.name" 
                                    placeholder="请输入商品名称"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="品牌" prop="brand">
                                <el-input 
                                    v-model="form.brand" 
                                    placeholder="请输入品牌名称"
                                />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    
                    <el-form-item label="副标题" prop="caption">
                        <el-input 
                            v-model="form.caption" 
                            placeholder="请输入商品副标题"
                            type="textarea"
                            :rows="2"
                        />
                    </el-form-item>
                    
                    <el-row :gutter="20">
                        <el-col :span="8">
                            <el-form-item label="单价" prop="price">
                                <el-input-number 
                                    v-model="form.price" 
                                    :precision="2" 
                                    :step="0.01" 
                                    :max="100000" 
                                    controls-position="right"
                                    style="width: 100%"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="库存" prop="stock">
                                <el-input-number 
                                    v-model="form.stock" 
                                    :precision="0" 
                                    :step="1" 
                                    :max="100000" 
                                    controls-position="right"
                                    style="width: 100%"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="状态">
                                <el-switch 
                                    v-model="form.status" 
                                    :active-value="1" 
                                    :inactive-value="0"
                                    active-text="上架"
                                    inactive-text="下架"
                                />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    
                    <el-form-item label="商品分类" prop="classification1">
                        <el-row :gutter="10">
                            <el-col :span="12">
                                <el-select 
                                    v-model="form.classification1" 
                                    placeholder="请选择一级分类"
                                    style="width: 100%"
                                    :loading="!classifications.length"
                                    clearable
                                    filterable
                                >
                                    <el-option 
                                        :label="classification.name" 
                                        :value="classification.id" 
                                        :key="classification.id"
                                        v-for="classification in classifications"
                                    >
                                        <span>{{ classification.name }}</span>
                                        <span style="float: right; color: #8492a6; font-size: 13px">
                                            ID: {{ classification.id }}
                                        </span>
                                    </el-option>
                                </el-select>
                                <div style="font-size: 12px; color: #999; margin-top: 5px;">
                                    当前选择: {{ form.classification1 }} | 分类数量: {{ classifications.length }}
                                </div>
                            </el-col>
                            <el-col :span="12">
                                <el-select 
                                    v-model="form.classification2" 
                                    placeholder="请选择二级分类"
                                    style="width: 100%"
                                    :disabled="!form.classification1"
                                    :loading="!classifications2.length && form.classification1"
                                    clearable
                                    filterable
                                >
                                    <el-option 
                                        :label="classification.name" 
                                        :value="classification.id" 
                                        :key="classification.id"
                                        v-for="classification in classifications2"
                                    >
                                        <span>{{ classification.name }}</span>
                                        <span style="float: right; color: #8492a6; font-size: 13px">
                                            ID: {{ classification.id }}
                                        </span>
                                    </el-option>
                                </el-select>
                                <div style="font-size: 12px; color: #999; margin-top: 5px;">
                                    当前选择: {{ form.classification2 }} | 子分类数量: {{ classifications2.length }}
                                </div>
                            </el-col>
                        </el-row>
                    </el-form-item>
                    
                    <el-form-item label="商品图片">
                        <el-upload
                            ref="uploadRef"
                            action=""
                            list-type="picture-card"
                            :on-preview="handlePictureCardPreview"
                            :headers="{ 'Authorization': 'JWT ' + user_store.token }"
                            :auto-upload="false"
                            :data="form"
                            multiple
                            v-model:file-list="fileList"
                            :limit="5"
                        >
                            <el-icon><Plus /></el-icon>
                        </el-upload>
                        <el-dialog v-model="dialogVisible">
                            <img width="100%" :src="dialogImageUrl" alt />
                        </el-dialog>
                    </el-form-item>
                    
                    <el-form-item label="包装信息" prop="pack">
                        <el-input 
                            v-model="form.pack" 
                            placeholder="请输入包装信息"
                            type="textarea"
                            :rows="3"
                        />
                    </el-form-item>
                    
                    <el-form-item label="售后服务" prop="serviceafter_sale">
                        <el-input 
                            v-model="form.serviceafter_sale" 
                            placeholder="请输入售后服务说明"
                            type="textarea" 
                            :rows="4"
                        />
                    </el-form-item>
                    
                    <el-form-item class="action-buttons">
                        <el-button 
                            type="info" 
                            @click="submitForm(formEl, 0)"
                            :loading="isSubmitting"
                            class="save-btn"
                        >
                            <i class="el-icon-document"></i>
                            保存商品
                        </el-button>
                        <el-button 
                            type="primary" 
                            @click="submitForm(formEl, 1)"
                            :loading="isSubmitting"
                            class="publish-btn"
                        >
                            <i class="el-icon-upload"></i>
                            立即上架
                        </el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { getClassifications, creatCommodity } from '@/api/shopping'
import { userStore } from '@/store/user'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'

const router = useRouter()
const user_store = userStore()
const formEl = ref()
const isSubmitting = ref(false)

const form = ref({
    name: '',
    caption: '',
    price: 0.00,
    stock: 0,
    brand: '',
    detail: '',
    pack: '',
    serviceafter_sale: '',
    status: 0,
    classification1: null,
    classification2: null,
})

const fileList = ref([])

const rules = ref({
    name: [
        { required: true, message: '请输入商品名称', trigger: 'blur' },
        { min: 1, max: 40, message: '商品名称长度为1-40个字符', trigger: 'blur' },
    ],
    caption: [
        { required: true, message: '请输入商品副标题', trigger: 'blur' },
        { min: 1, max: 140, message: '副标题长度为1-140个字符', trigger: 'blur' },
    ],
    classification1: [
        { required: true, message: '请选择商品分类', trigger: 'change' },
    ],
    price: [
        { required: true, message: '请输入商品价格', trigger: 'blur' },
        { type: 'number', min: 0.01, message: '价格必须大于0', trigger: 'blur' },
    ],
    stock: [
        { required: true, message: '请输入库存数量', trigger: 'blur' },
        { type: 'number', min: 0, message: '库存不能为负数', trigger: 'blur' },
    ]
})

const classifications = ref([])
const classifications2 = ref([])

// 获取分类数据
const fetchClassifications = async () => {
    try {
        const data = await getClassifications()
        console.log('分类数据:', data) // 调试用
        console.log('分类数据类型:', typeof data) // 调试用
        console.log('分类数据长度:', data?.length) // 调试用
        if (Array.isArray(data)) {
            classifications.value = data
            console.log('分类数据设置成功:', classifications.value) // 调试用
        } else {
            console.error('分类数据格式错误，期望数组:', data)
            ElMessage.error('分类数据格式错误')
        }
    } catch (error) {
        console.log('获取分类失败', error.message)
        ElMessage.error('获取分类失败')
    }
}

// 监听一级分类变化
watch(() => form.value.classification1, (value) => {
    console.log('一级分类变化:', value) // 调试用
    if (value) {
        const selectedClassification = classifications.value.find(item => item.id === value)
        console.log('选中的分类:', selectedClassification) // 调试用
        if (selectedClassification) {
            classifications2.value = selectedClassification.classification_set || []
            console.log('二级分类:', classifications2.value) // 调试用
        } else {
            classifications2.value = []
        }
        form.value.classification2 = null
    } else {
        classifications2.value = []
        form.value.classification2 = null
    }
})

const dialogImageUrl = ref('')
const dialogVisible = ref(false)

function handlePictureCardPreview(file) {
    dialogImageUrl.value = file.url
    dialogVisible.value = true
}

const uploadRef = ref()

const submitForm = async (formEl, status) => {
    if (!formEl) return
    
    try {
        const valid = await formEl.validate()
        if (valid) {
            isSubmitting.value = true
            form.value.status = status
            
            const formData = new FormData()
            for (let i = 0; i < fileList.value.length; i++) {
                formData.append('file', fileList.value[i].raw)
            }
            for (let key in form.value) {
                formData.append(key, form.value[key])
            }
            
            await creatCommodity(formData)
            ElMessage.success(status === 0 ? '商品保存成功' : '商品上架成功')
            router.push('/shopping')
        }
    } catch (error) {
        if (error.message === '请检查表单信息') {
            ElMessage.warning('请检查表单信息')
        } else {
            ElMessage.error('操作失败：' + (error.message || '未知错误'))
        }
    } finally {
        isSubmitting.value = false
    }
}

// 组件挂载时获取分类数据
onMounted(() => {
    fetchClassifications()
})
</script>

<style lang="less" scoped>
.add-product-container {
    min-height: 100vh;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    padding: 20px;
}

.content-wrapper {
    max-width: 1200px;
    margin: 0 auto;
}

.header-section {
    text-align: center;
    margin-bottom: 30px;
    color: white;
    
    .page-title {
        font-size: 32px;
        font-weight: 700;
        margin-bottom: 10px;
        text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
        
        i {
            margin-right: 10px;
        }
    }
    
    .page-subtitle {
        font-size: 16px;
        opacity: 0.9;
        margin: 0;
    }
}

.form-card {
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(10px);
    border-radius: 20px;
    padding: 40px;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.2);
}

.product-form {
    .action-buttons {
        text-align: center;
        margin-top: 30px;
        
        .el-button {
            margin: 0 10px;
            padding: 12px 25px;
            font-size: 14px;
            border-radius: 25px;
            transition: all 0.3s ease;
            
            &:hover {
                transform: translateY(-2px);
                box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
            }
        }
        
        .save-btn {
            background: linear-gradient(45deg, #a8a8a8, #888);
            border: none;
            color: white;
        }
        
        .publish-btn {
            background: linear-gradient(45deg, #667eea, #764ba2);
            border: none;
        }
    }
}

:deep(.el-upload--picture-card) {
    background: rgba(102, 126, 234, 0.1);
    border: 2px dashed rgba(102, 126, 234, 0.3);
    border-radius: 10px;
    transition: all 0.3s ease;
    
    &:hover {
        border-color: #667eea;
        background: rgba(102, 126, 234, 0.15);
    }
}

@media (max-width: 768px) {
    .add-product-container {
        padding: 10px;
    }
    
    .form-card {
        padding: 20px;
        border-radius: 15px;
    }
    
    .header-section .page-title {
        font-size: 24px;
    }
}
</style> 